package com.mymoney.resources;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.mymoney.beans.CategoryBean;
import com.mymoney.exceptions.MyMoneyException;
import com.mymoney.persistence.PersistenceContext;
import com.mymoney.persistence.TransactionalAction;
import com.mymoney.persistence.managers.CategoryManager;
import com.mymoney.utils.ServiceUtils;

@Path("/categories")
public class CategoryResource extends AbstractWebResource{

	@POST
	@Path("/category")
	@Produces({ MediaType.APPLICATION_JSON })
	public Response add(final CategoryBean category) {

		final PersistenceContext persistenceContext = PersistenceContext.getPersistenceContext();

		try {

			TransactionalAction action = new TransactionalAction() {

				public void run() throws MyMoneyException {
					CategoryManager categoryManager = persistenceContext.getCategoryManager();
					categoryManager.add(category);
				};

			};
			persistenceContext.run(action);
			return Response.ok("EVALA").build();
		} catch (Exception e) {
			Response response = ServiceUtils.getErrorResponse(111, e);
			return response;
		}
	}

	@GET
	@Path("/category/{code}")
	@Produces({ MediaType.APPLICATION_JSON })
	public Response getByCode(final @PathParam("code") long code) {

		PersistenceContext persistenceContext = getPersistenceContext();
		try {
			CategoryManager categoryManager = persistenceContext.getCategoryManager();
			CategoryBean category = categoryManager.getByCode(code);

			return Response.ok(category).type(MediaType.APPLICATION_JSON).build();
		} catch (Exception e) {
			Response response = ServiceUtils.getErrorResponse(111, e);
			return response;
		}
	}
	
	@GET
	@Produces({ MediaType.APPLICATION_JSON })
	public Response list() {
		Response response = null;
		PersistenceContext persistenceContext = getPersistenceContext();
		
		try {
			if(persistenceContext != null)
			{
				CategoryManager categoryManager = persistenceContext.getCategoryManager();
				List<CategoryBean> category = categoryManager.list();
				response =  Response.ok(category).type(MediaType.APPLICATION_JSON).build();
			}
			else
			{
				throw new NullPointerException();
			}
		} catch (Exception e) {
			response = ServiceUtils.getErrorResponse(111, e);
		}
		
		return response;
	}
}
